package com.egao.common.manage.college;

import cn.hutool.core.util.StrUtil;
import com.egao.common.component.elasticsearch.entity.vo.StudentPushMsgVO;
import com.egao.common.component.elasticsearch.service.ElasticSearchService;
import com.egao.common.core.annotation.ApiPageParam;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.entity.StudentRecord;
import com.egao.common.module.student.entity.vo.StudentExcelVO;
import com.egao.common.module.student.entity.vo.StudentFormVO;
import com.egao.common.module.student.entity.vo.StudentListVO;
import com.egao.common.module.student.service.StudentRecordService;
import com.egao.common.module.student.service.StudentService;
import com.egao.common.module.system.constants.DictConstants;
import com.egao.common.module.system.constants.UserConstants;
import com.egao.common.module.system.entity.Dict;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.service.DictService;
import com.egao.common.module.system.service.MajorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学院生源管理
 *
 * @author lym
 */
@Api(tags = "学院生源管理")
@RestController
@RequestMapping("${api}")
public class CollegeStudentController extends BaseController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private MajorService majorService;
    @Autowired
    private StudentRecordService studentRecordService;
    @Autowired
    private DictService dictService;
    @Autowired
    private ElasticSearchService elasticSearchService;

    private final String title = "学院生源管理";

    @PreAuthorize("hasAuthority('college:student:list')")
    @OperLog(value = title, desc = "分页查询生源")
    @ApiOperation(value = "分页查询生源", notes = "学生提交状态倒序 学号升序")
    @ApiPageParam
    @GetMapping("/college/student/page")
    public PageResult<StudentListVO> page(HttpServletRequest request) {
        User loginUser = getLoginUser();

        if (StrUtil.isBlank(loginUser.getCollegeCode())) {
            throw new BusinessException("没有找到您的学院信息，请联系就业中心");
        }

        PageParam<StudentListVO> pageParam = new PageParam<>(request);

        pageParam.put("collegeCode", loginUser.getCollegeCode());

        String degree = null;
        degree = UserConstants.DEGREE_SCOPE_ALL.equals(loginUser.getDegreeScope()) ? null : loginUser.getDegreeScope();
        pageParam.put("degree", degree);

        if (UserConstants.STUDENT_SCOPE_PART.equals(loginUser.getStudentScope())) {
            pageParam.put("collegeUserId", loginUser.getUserId());
        }

        if (!StrUtil.isBlank(loginUser.getBjhm())) {
            pageParam.put("bjhm", loginUser.getBjhm());
        }

        pageParam.setOrder("student_state", false)
                .setOrder("xh", true);

        return new PageResult<>(studentService.listPage(pageParam), pageParam.getTotal());
    }

    @PreAuthorize("hasAuthority('college:student:list')")
    @ApiOperation(value = "当前用户所属学院专业集合")
    @GetMapping("/college/student/majors")
    public JsonResult majors() {
        return JsonResult.ok().setData(majorService.listAll(getLoginUser().getCollegeCode(), null));
    }

    @PreAuthorize("hasAuthority('college:student:list')")
    @ApiOperation(value = "查询列表字典")
    @GetMapping("/college/student/dicts")
    public JsonResult dicts() {
        Map<String, List<Dict>> map = new HashMap<>();
        map.put("pyfsList", dictService.cacheList(DictConstants.TYPE_PYFS));
        map.put("syszdList", dictService.cacheList(DictConstants.TYPE_SYSZD));
        return JsonResult.ok().setData(map);
    }

    @PreAuthorize("hasAuthority('college:student:detail')")
    @OperLog(value = title, desc = "学生详情信息")
    @ApiOperation(value = "学生详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "学生ID", required = true, dataType = "int")
    })
    @GetMapping("/college/student/detail")
    public JsonResult student(Integer id) {
        return JsonResult.ok().setData(studentService.getStudentFormVO(id));
    }

    @PreAuthorize("hasAuthority('college:student:detail')")
    @ApiOperation(value = "学生信息记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型", required = false, dataType = "string"),
            @ApiImplicitParam(name = "studentId", value = "学生ID", required = true, dataType = "int")
    })
    @GetMapping("/college/student/record")
    public PageResult record(HttpServletRequest request) {
        PageParam<StudentRecord> pageParam = new PageParam<>(request);
        return new PageResult<>(studentRecordService.listPage(pageParam), pageParam.getTotal());
    }

    @PreAuthorize("hasAuthority('college:student:update')")
    @OperLog(value = title, desc = "编辑审核学生信息", result = true)
    @ApiOperation(value = "编辑审核学生信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentFormVO", value = "StudentFormVO", required = true, dataType = "StudentFormVO")
    })
    @PutMapping("/college/student/update")
    public JsonResult update(@RequestBody StudentFormVO studentFormVO) {
        return studentService.collegeSubmit(studentFormVO, getLoginUserId());
    }

    @PreAuthorize("hasAuthority('college:student:export')")
    @OperLog(value = title, desc = "导出", result = true)
    @ApiOperation(value = "导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "导出类型 text文本 code代码", required = true, dataType = "string"),
            @ApiImplicitParam(name = "StudentExcelVO", value = "StudentExcelVO", required = false, dataType = "StudentExcelVO")
    })
    @GetMapping("/college/student/export")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        User loginUser = getLoginUser();

        if (StrUtil.isBlank(loginUser.getCollegeCode())) {
            throw new BusinessException("没有找到您的学院信息，请联系就业中心");
        }

        PageParam<StudentExcelVO> pageParam = new PageParam<>(request);

        pageParam.put("collegeCode", loginUser.getCollegeCode());

        String degree = null;
        degree = UserConstants.DEGREE_SCOPE_ALL.equals(loginUser.getDegreeScope()) ? null : loginUser.getDegreeScope();
        pageParam.put("degree", degree);

        if (UserConstants.STUDENT_SCOPE_PART.equals(loginUser.getStudentScope())) {
            pageParam.put("collegeUserId", loginUser.getUserId());
        }

        pageParam.setOrder("student_state", false)
                .setOrder("xh", true);

        studentService.exportStudent(pageParam, response);
    }

    @PreAuthorize("hasAuthority('college:student:list')")
    @OperLog(value = title, desc = "查询学生接收推送信息")
    @ApiOperation(value = "查询学生接收推送信息", notes = "查询学生接收推送信息")
    @ApiPageParam
    @GetMapping("/college/student/page-push")
    public PageResult<StudentPushMsgVO> pagePush(HttpServletRequest request) {
        PageParam<StudentListVO> pageParam = new PageParam<>(request);
        try {
            int page = (int) pageParam.getCurrent();
            int limit = (int) pageParam.getSize();
            return elasticSearchService.searchStudentPushMsg(pageParam.getString("id"), page, limit);
        } catch (IOException e) {
            throw new BusinessException("查询异常");
        }
    }


    @PreAuthorize("hasAuthority('college:student:list')")
    @OperLog(value = title, desc = "查看学生就业意向详情")
    @ApiOperation(value = "查看学生就业意向详情")
    @GetMapping("/college/inten/detail")
    public JsonResult detail(Integer id) {
        Student student = studentService.getById(id);
        if (student != null) {
            return JsonResult.ok().setData(studentService.getStudentInten(student.getUserId()));
        }
        return JsonResult.error("学生信息异常");
    }

    @PreAuthorize("hasAuthority('college:student:list')")
    @ApiOperation(value = "学生就业意向详情字典")
    @GetMapping("/college/inten/dict")
    public JsonResult dictMap() {
        return JsonResult.ok().setData(studentService.dictMap());
    }

    @PreAuthorize("hasAuthority('college:student:update')")
    @OperLog(value = title, desc = "开关系统单位自由录入")
    @ApiOperation(value = "开关系统单位自由录入")
    @PutMapping("/college/student/sign-entry/{id}/{state}")
    public JsonResult signEntry(@PathVariable("id") Integer id, @PathVariable("state") String state) {
        studentService.changeSignEntry(studentService.getById(id), getLoginUserId(), state);
        return JsonResult.ok();
    }

}
